package com.zhiwei.common.util;

import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * function: Bean转换工具
 * author: zhiwei_yang
 * time: 2020/2/9-16:28
 */
public class BeanConverterUtil {

    /**
     * 将元对象转换为目标对象<br/>
     * 1. 支持深度拷贝
     *
     * @param sourceObject 原对象
     * @param clazz        目标对象
     * @param <T>
     * @return
     */
    public static <T> T convertToBean(Object sourceObject, Class<T> clazz) {
        if (sourceObject == null) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(sourceObject), clazz);
    }

    /**
     * 将元对象转换为目标对象<br/>
     * 1. 支持深度拷贝
     *
     * @param sourceObjectList 原对象数组
     * @param clazz            目标对象
     * @param <T>
     * @return
     */
    public static <T> List<T> convertToBeanList(Collection<?> sourceObjectList, Class<T> clazz) {
        if (CollectionUtils.isEmpty(sourceObjectList)) {
            return Collections.emptyList();
        }
        return JSON.parseArray(JSON.toJSONString(sourceObjectList), clazz);
    }
}
